import rpc, { login, sleep } from './get_rpc.js'

const fields_for_form = [
  'name',
  //   'display_name',
  //   'reference',
  //   'client_order_ref',
  'note',
  'origin',
  'tag_ids',

  'state',
  //   'invoice_status'

  //   'company_id',
  //   'user_id',
  //   'team_id',
  'partner_id',
  //   'pricelist_id',
  //   'payment_term_id'

  //   'validity_date',
  //   'date_order',
  'picking_policy',
  'expected_date',
  {
    name: 'order_line',
    fields: [
      // 'name',
      'product_id',
      'product_uom',
      'product_uom_qty',
      'qty_to_deliver',
      // 'qty_delivered',
      // 'qty_invoiced',
      'price_unit',
      {
        name: 'tax_id',
        fields: ['name', 'display_name']
      },

      'price_tax',
      'price_subtotal',
      // 'discount',
      'invoice_lines'
    ]
  }
]

async function load_metadata() {
  const model = 'sale.order'
  const Model = rpc.env.model(model)
  console.log(Model)

  const fields = fields_for_form

  const datastore = {
    metadata: {}
  }
  datastore.metadata = await Model.load_metadata({
    fields,
    callback: function (res) {
      datastore.metadata = res
    },
    context: { ctxtest: 1 }
  })
  console.log('metadata:', datastore.metadata)

  return Model
}

async function call_load_data(Model) {
  const datastore = {
    records: [],
    record: {}
  }

  const domain = [['name', '=', 'S00005']]
  const fields = ['name', 'tag_ids', 'order_line']
  datastore.records = await Model.load_data({
    domain,
    fields,
    callback: function (res) {
      datastore.records = res
      // console.log('datastore.records cb:', datastore.records)
    }
  })
  console.log('datastore.records:', datastore.records)

  const res_id = datastore.records[0].id
  datastore.record = await Model.load_data_one(res_id, {
    // fields: fields_for_form,
    callback: function (res) {
      datastore.record = res
      // console.log('call_load_data one cb:', datastore.record)
    }
  })

  console.log('datastore.record:', datastore.record)

  return datastore.record
}

async function to_new(Model) {
  const metadata = Model.metadata
  const Editmodel = rpc.env.editmodel(Model.model, { metadata })

  const datastore = {
    model: Model.model,
    record: {},
    domain: {},
    values: {}
    // record_display: {}
  }

  function update_datastore(payload = {}) {
    const { domain = {}, values = {}, record_display = {} } = payload
    datastore.domain = { ...datastore.domain, ...domain }
    datastore.values = { ...datastore.values, ...values }
    datastore.record_display = {
      ...datastore.record_display,
      ...record_display
    }
  }

  // 1. 编辑模型初始化, 设置 数据.  datastore.record_display 用于 页面显示
  datastore.record_display = Editmodel.set_edit({
    record: datastore.record,
    values: datastore.values
  })

  // 2. 页面编辑动作. 触发 onchange. 返回结果 更新 datastore.record_display
  // const res3 = await Editmodel.onchange('note', 'ssssss')
  const res3 = await Editmodel.onchange()
  update_datastore(res3)
  console.log('Editmodel2,datastore', datastore)
}

async function to_edit(Model, record) {
  const metadata = Model.metadata
  // console.log('metadata', metadata)
  // console.log('metadata.order_line', metadata.order_line)

  const Editmodel = rpc.env.editmodel(Model.model, { metadata })

  const datastore = {
    model: Model.model,
    record,
    domain: {},
    values: {},
    record_display: {}
  }

  function update_datastore(payload = {}) {
    const { domain = {}, values = {}, record_display = {} } = payload
    datastore.domain = { ...datastore.domain, ...domain }
    datastore.values = { ...datastore.values, ...values }
    datastore.record_display = {
      ...datastore.record_display,
      ...record_display
    }
  }

  // 1. 编辑模型初始化, 设置 数据.  datastore.record_display 用于 页面显示
  datastore.record_display = Editmodel.set_edit({
    record,
    values: datastore.values
  })
  // console.log('Editmodel', Editmodel)

  console.log('Editmodel1,record_display', datastore.record_display)

  await sleep(1000)

  // 2. 页面编辑动作. 触发 onchange. 返回结果 更新 datastore.record_display
  // const res3 = await Editmodel.onchange('note', 'ssssss')
  const res3 = await Editmodel.onchange('picking_policy', 'one')

  console.log('onchange', res3)
  update_datastore(res3)
  console.log('Editmodel2,datastore', datastore)

  // console.log('Editmodel2,datastore.record_display', datastore.record_display)

  // // console.log('o2m data', datastore.record_display.order_line)

  // // 5. o2m 字段的编辑 todo

  await edit_lines({ metadata, datastore }, onchange)

  async function onchange(fname, value) {
    console.log('onchange,', fname, value)
    // // the last. todo
    const res = await Editmodel.onchange(fname, value)
    console.log('onchange2,', fname, res)
    // console.log('onchange2,', fname, res.values)
    // console.log('onchange2,', fname, res.values.order_line)
  }

  console.log('o2m,datastore', Editmodel.datastore)

  // // // 4. 页面保存动作. 触发 commit. 返回结果 id
  const res4 = await Editmodel.commit()
  console.log('Editmodel2,commit', res4)

  // // 5. 页面根据 id 刷新显示
}

async function edit_lines(parent_info, onchange) {
  const { metadata: parent_metadata, datastore: parent_data } = parent_info
  const meta = parent_metadata.order_line
  const Rel = rpc.env.one2many(meta)
  const records = parent_data.record.order_line || []
  const values = parent_data.values.order_line || []

  const lines = Rel.set_edit({ records, values })

  const datastore = {
    records,
    values,
    records_display: lines
  }

  console.log('lines edit lines,', lines)
  // 51. pick one to edit
  // for (const line of lines) {
  //   console.log(line)
  // }

  const line0 = lines[0]
  await edit_line(parent_info, line0, cb, 'product_uom_qty', 13)

  await new_line(parent_info, cb)

  // console.log('line edit after new line,', datastore)
  const lines2 = datastore.records_display
  const line = lines2[lines2.length - 1]
  // console.log('line edit   new line,', line)
  await edit_line(parent_info, line, cb, 'product_id', { id: 1 })
  await edit_line(parent_info, line, cb, 'product_uom_qty', 13)

  // o2mform 编辑后. 提交 到  o2mtree
  async function cb(res_id, value) {
    console.log('line edit cb,', res_id, value)
    const res = Rel.upinsert_one(res_id, value)
    datastore.values = res.values
    datastore.records_display = res.records_display
    console.log('line edit cb2,', res, datastore)
    if (res_id) {
      // 新增行 获取 默认值后, 仅需 更新数据. 无需 触发 onchange
      const lines_records_edit = Rel.records_edit
      console.log('line edit cb3,', lines_records_edit)
      const res2 = await onchange('order_line', lines_records_edit)
      console.log('line edit cb4,', res2)
    }

    //
    //
  }
}

async function new_line(parent_info, cb) {
  const { metadata: parent_metadata, datastore: parent_data } = parent_info
  const meta = parent_metadata.order_line
  const Rel = rpc.env.one2many(meta)
  const Editmodel = Rel.Editmodel
  const datastore = {
    record: {},
    domain: {},
    values: {},
    record_display: {}
  }
  function update_datastore(payload = {}) {
    const { domain = {}, values = {}, record_display = {} } = payload
    datastore.domain = { ...datastore.domain, ...domain }
    datastore.values = { ...datastore.values, ...values }
    datastore.record_display = {
      ...datastore.record_display,
      ...record_display
    }
  }

  datastore.record_display = Editmodel.set_edit({
    record: {},
    values: datastore.values,
    parent_info
  })

  console.log('line,record_display', datastore.record_display)
  const res2 = await Editmodel.onchange()
  console.log('line,res2', res2)
  update_datastore(res2)
  await cb(null, datastore.values)

  // const res3 = await Editmodel.onchange('product_uom_qty', 13)
  // console.log('line,res3', res3)
  // update_datastore(res3)
  // cb(line.id, datastore.values)
}

async function edit_line(parent_info, line, cb, fname, val) {
  const { metadata: parent_metadata, datastore: parent_data } = parent_info
  const meta = parent_metadata.order_line
  const Rel = rpc.env.one2many(meta)
  const Editmodel = Rel.Editmodel
  const datastore = {
    record: line,
    domain: {},
    values: {},
    record_display: {}
  }
  function update_datastore(payload = {}) {
    const { domain = {}, values = {}, record_display = {} } = payload
    datastore.domain = { ...datastore.domain, ...domain }
    datastore.values = { ...datastore.values, ...values }
    datastore.record_display = {
      ...datastore.record_display,
      ...record_display
    }
  }
  datastore.record_display = Editmodel.set_edit({
    record: line,
    values: datastore.values,
    parent_info
  })
  // // // console.log('Editmodel', Editmodel)
  console.log('line,record_display', datastore.record_display)
  const res3 = await Editmodel.onchange(fname, val)
  console.log('line,res3', res3)
  update_datastore(res3)
  await cb(line.id, datastore.values)
  // const res4 = await Editmodel.onchange('product_uom_qty', 15)
  // console.log('line,res4', res4)
  // update_datastore(res4)
  // cb(line.id, datastore.values)
  // //
}

async function test() {
  await login()
  // 1. 初始化 metadata
  const Model = await load_metadata()

  const datastore = {
    record: {}
  }

  // // 2. 只读 获取数据. 包括 x2m 嵌套数据
  datastore.record = await call_load_data(Model)
  // console.log('datastore.record:', datastore.record)
  // console.log('datastore.record.order_line:', datastore.record.order_line)
  // datastore.record.order_line.forEach(item => {
  //   console.log('datastore.record.order_line one:', item)
  // })

  // 3. 点击编辑按钮. 进入编辑状态
  to_edit(Model, datastore.record)

  // 4. new
  // to_new(Model)
}

export function useTest() {
  return { test }
}
